package com.blogspot.security.service.impl;

import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Service;

import com.blogspot.security.dao.impl.UserRegisterDaoImpl;
import com.blogspot.security.domain.ApplicationUser;
import com.blogspot.security.service.UserDetailsRegisterService;

@Service
public class UserDetailsRegisterServiceImpl implements UserDetailsRegisterService {
	private Logger logger = LoggerFactory.getLogger(UserDetailsRegisterServiceImpl.class);
	
	@Autowired
	UserRegisterDaoImpl userRegisterDaoImpl;
	
	public void insertApplicationUser(ApplicationUser user) {
		try {
			user.setPassword(encodeSha256(user.getPassword(), user.getUserName()).toLowerCase());
			logger.error("Allan Sung Password is : " + user.getPassword());
			userRegisterDaoImpl.insertApplicationUser(user);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
    public String encodeSha256(String password, String username) throws NoSuchAlgorithmException {       
        ShaPasswordEncoder sha = new ShaPasswordEncoder(256);     
        sha.setEncodeHashAsBase64(false);     
        //System.out.println("哈希算法 256: " + pwd + " len=" + pwd.length());    
        return sha.encodePassword(password, username);
    }     
         
        
    public void sha_SHA_256() {     
        ShaPasswordEncoder sha = new ShaPasswordEncoder();     
        sha.setEncodeHashAsBase64(false);     
        String pwd = sha.encodePassword("1234", null);      
        System.out.println("哈希算法 SHA-256: " + pwd + " len=" + pwd.length());     
    } 
}
